import React, { useEffect, useMemo } from "react"
import { NavBar } from "antd-mobile"
import { SmileOutline } from "antd-mobile-icons"
import "./index.css"
import { useState } from "react"
function Index() {
  const user_id = 1
  const server_id = 1217
  const [list, setList] = useState([])
  const [value, setVla] = useState("")
  // 连接websokce
  const ws = useMemo(() => {
    return new WebSocket(
      `ws://113.44.139.133:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    )
  }, [])
  useEffect(() => {
    ws.onopen = () => {
      console.log("连接成功")
      ws.send(JSON.stringify({ type: "getChatList" }))
    }
    ws.onmessage = event => {
      const result = JSON.parse(event.data)
      console.log(result)
      if (result.type === "getChatList") {
        setList(result.data)
      } else if (result.type === "addMessage") {
        setList([...list, result.data])
      }
    }
    return () => {
      ws.close()
    }
  }, [])
  const sendMessgae = () => {
    ws.send(
      JSON.stringify({
        type: "addMessage",
        user_id,
        server_id,
        message: value,
        date: new Date(),
      })
    )
  }
  return (
    <div>
      <NavBar>在线聊天</NavBar>
      <div className="ser-nav-bat">
        {list.map((item, index) => (
          <div key={index} className="service">
            <img src={item.user_avatar}></img>
            <span>{item.message}</span>
          </div>
        ))}
      </div>
      <div className="ser-inp-bat">
        <input className="inp" onChange={val => setVla(val)} />
        <div className="img">图片</div>
        <SmileOutline fontSize={60} />
        <div className="send-btmn" onClick={() => sendMessgae()}>
          发送
        </div>
      </div>
    </div>
  )
}

export default Index
